$(document).ready(function(){
    $("tr").each(function (idx, item) {
           if(idx > 0 && idx%2==0)
               $(this).css("background-color"," #BBECDF");
           else
               $(this).css("background-color","#FFFACD");
     });

     var current_page = parseInt($("#current_page").text());
     var total_page = parseInt($( "#total_page" ).text());
     $("#prev_page").css("inline");
     $("#next_page").css("inline");
     if(current_page <= 1) $("#prev_page").css("display", "none");
     if(current_page >= total_page)$("#next_page").css("display", "none");

     var trs = document.getElementsByClassName('item_list');
     for (var i = 0; i < trs.length; i++)
     	trs[i].onclick = trDbClick;
         // trs[i].ondblclick = trDbClick;
     if(trs.length > 0){
         currentSelect.name = trs[0].cells[1].childNodes[0].textContent;
         currentSelect.id = parseInt(trs[0].cells[0].childNodes[0].textContent);
         trs[0].style.backgroundColor = "#FFC125";
         setAlarmLink();
         setHistoryLink();
         $("#link_to_setting").attr("href", "/api/update_device_node/?device_node_id="+searchDeviceId()+"&user_id="+searchUserId());
        $("#link_to_user_setting").attr("href","/index/create_user/?device_node_id="+searchDeviceId()+"&user_id="+searchUserId());  
     }
     currentSelect.page_rows = parseInt(getURLString('page_rows')) ? parseInt(getURLString('page_rows')) : trs.length
     currentSelect.page_id = current_page;// parseInt(getURLString('page_id'));   
 });

function trDbClick() {
    currentSelect.name = this.cells[1].childNodes[0].textContent;
    currentSelect.id = parseInt(this.cells[0].childNodes[0].textContent);
     $("tr").each(function (idx, item) {
           if(idx > 0 && idx%2==0)
               $(this).css("background-color","#BBECDF");
           else
               $(this).css("background-color","#FFFACD");
    });
    this.style.backgroundColor = "#FFC125";
    setAlarmLink();
    setHistoryLink();
    $("#link_to_setting").attr("href", "/api/update_device_node/?device_node_id="+searchDeviceId()+"&user_id="+searchUserId());
    $("#link_to_user_setting").attr("href","/index/create_user/?device_node_id="+searchDeviceId()+"&user_id="+searchUserId());  
    // alert(currentSelect.name);
}

function pageClick(n){
	var cur = parseInt($("#current_page").text());
    var total = parseInt($( "#total_page" ).text());

	if(n==1) {      // prev_page
        cur = cur - 1;
		document.getElementById( "current_page" ).innerHTML = cur.toString();
		document.getElementById( "next_page" ).style.display = "inline";
		if(cur <= 1){
			document.getElementById( "prev_page" ).style.display = "none";
		}
	}
	if(n==2){  // neext_pagee
	    cur = cur + 1;
	    document.getElementById( "prev_page" ).style.display = "inline";
		document.getElementById( "current_page" ).innerHTML = cur.toString();
		if(cur >= total) {
			document.getElementById( "next_page" ).style.display = "none";
		}
	}
	cur = parseInt($("#current_page").text());
	// data: {"page_id": (cur-1).toString(), "page_rows":"5"},
    window.location.href="/index/get_latest_monitor_data/?page_id="+cur.toString()+"&page_rows="+ currentSelect.page_rows.toString();
}


function serachTragById(id) {
    var trs = document.getElementsByClassName('item_list');
    var links = document.getElementsByClassName('link_download'); // link_item
    for(var i=0; i<trs.length; i++)
          if(id == parseInt(trs[i].cells[0].childNodes[0].textContent))
              return [trs[i],links[i]];
    return null;
}

function getMonitor(dict) {
    if (!dict)  return '';
    var str = ''; var alarm = 0;
    for (var key in dict) {
        if (key == 'datetime')
            continue;
        if (str != '') str += ', ';
        str = str + en2ch(key) + ': ' + dict[key].value.toString();
        alarm += dict[key].alarm;
    }
    return {monitor:str,alarm:en2ch(alarm > 0 ? 1 : 0)};
}

function setTable(msg){
    for( var key in msg){
        var trag_link = serachTragById(key);
        if(!trag_link) continue;
        monitorData = getMonitor(msg[key]).monitor
        var pos = monitorData.lastIndexOf('\\');
        trag_link[0].cells[trag_link[0].cells.length-2].childNodes[0].textContent = monitorData.substring(pos+1);
        trag_link[1].href = "/api/download_file/?file_path=" + ((msg[key])["file"]).value.toString();
        //  trag_link[1].innerHTML = getMonitor(msg[key]).alarm;
        //  trag_link[1].href = "/index/get_alarm_list/?device_node_id="+ trag_link[0].cells[0].childNodes[0].textContent;
    }
    return msg;
}

currentSelect={prev_id:-1, id:1, page_id:1, page_rows:5, chart_names:null, charts:null};
function setCharts(selector, dict){
	if (dict){
		var chart_names = (function(dict){list = []; for(var key in dict) list.push(key); return list;})(dict).map(function(key) {return "<div id=charts-"+key+"></div>\n<br class=charts_black>";}).join("\n");
		if(currentSelect.chart_names != chart_names || currentSelect.prev_id != currentSelect.id){
			currentSelect.chart_names = chart_names;
			currentSelect.prev_id = currentSelect.id
			delete currentSelect.charts;
			currentSelect.charts = Charts(selector, dict).map(function(item){return item.setOption();});
		}
	}
	else{
		currentSelect.chart_names = null;
		currentSelect.charts = null;
	}
	return currentSelect.charts;
}


var preAxis_X = "2018";
setInterval(function(){
    setTable(postData("/index/get_latest_monitor_data/", { "page_id": currentSelect.page_id, "page_rows": currentSelect.page_rows, "user_id": searchUserId() }));
    // var chartsData = setChartsData(setTable(postData("/index/get_latest_monitor_data/", {"page_id": currentSelect.page_id, "page_rows": currentSelect.page_rows, "user_id":searchUserId()})), currentSelect.id);
    // if(!chartsData) return;
    // for(var key in chartsData) {
    //     var item = chartsData[key]
    //     if (item.x != preAxis_X) { preAxis_X = item.x;  break;} else  return;
    // }
	// setCharts(".charts", chartsData).forEach(function(item){return item.resetQueue().setOption();});
}, 1000);
/*
setInterval(function(){
	setCharts(".charts", setChartsData(setTable(postData("/index/get_latest_monitor_data/", {"page_id": currentSelect.page_id, "page_rows": currentSelect.page_rows})), currentSelect.id)).forEach(function(item){return item.resetQueue().setOption();});
}, 1000);*/
